import { defineComponent, ref, reactive, onMounted } from 'vue'
import { ElCard, ElSpace, ElDivider, ElLink } from 'element-plus'
import { Plus, Minus } from '@element-plus/icons-vue'
import websock from '~/utils/socket'
import styles from './index.module.scss'
import HomeMap from './HomeMap'
import HomeTree from './HomeTree'
import Info from './info'
export default defineComponent(function Runmap() {
  const homeMapRef = ref()
  const state = reactive({
    mapZoom: 5,
    infoVisible: false,
    infoRecord: null
  })
  //  tree点击
  const handleNodeClick = (row: any) => {
    if (row.type && row.type.indexOf(',') > 0) {
      const markers = row.type.split(',')
      const content = row.title
      homeMapRef.value.markerLayer({ markers, content, runStatus: row.runStatus })

      state.infoVisible = true
      state.infoRecord = row
    }
  }
  //  关闭详情框
  const handleInfoClose = () => {
    state.infoVisible = false
  }
  //  显示详情
  const handleMonitorInfo = (row: any) => {
    row.title = row.name
    state.infoVisible = true
    state.infoRecord = row
  }
  // 控制地图放大缩小
  const handleClickChangeMapZoom = async (type: '+' | '-') => {
    if (type === '+') {
      state.mapZoom++
    } else {
      state.mapZoom--
    }
    await homeMapRef.value.map.setZoom(state.mapZoom)
  }
  // 获取当前地图层级并赋值
  const getMapZoom = () => {
    state.mapZoom = Math.round(homeMapRef.value.map.getZoom())
  }
  onMounted(() => {
    websock.onopen('/websocket/protocol/hardware')
  })
  return () => (
    <section class={styles['home-box']}>
      <HomeMap
        id={styles['home-map']}
        ref={homeMapRef}
        getMapZoom={getMapZoom}
        onHandleMonitorInfo={handleMonitorInfo}
      />
      <HomeTree class={styles['home-box-tree']} onHandleNodeClick={handleNodeClick} />
      {/* 控制地图放大缩小 */}
      <section class={styles['home-zoom']}>
        <ElCard class="zoom-number-card">{state.mapZoom}</ElCard>
        <ElCard class="zoom-option-card">
          <ElSpace direction="vertical" spacer={<ElDivider />}>
            <ElLink
              underline={false}
              icon={Plus}
              disabled={state.mapZoom === 20}
              onClick={() => handleClickChangeMapZoom('+')}
            />
            <ElLink
              underline={false}
              icon={Minus}
              disabled={state.mapZoom === 5}
              onClick={() => handleClickChangeMapZoom('-')}
            />
          </ElSpace>
        </ElCard>
      </section>
      {/* 回路监控箱详情 */}
      {state.infoVisible && <Info record={state.infoRecord} close={handleInfoClose} />}
    </section>
  )
})
